<?php

namespace App\Services\Jobposition;

use App\Exceptions\ApiExceptions;
use App\Models\CompanyModel;
use App\Models\JobPositionCollectModel;
use App\Models\JobpositionModel;
use App\Models\JobPositionRecommendModel;
use App\Models\MessageModel;
use App\Models\SignUpJobpositionModel;
use App\Models\User;
use App\Services\AbstractBaseService;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Models\JobPositionThumbsupModel;

class JobpositionService extends AbstractBaseService
{
    public function list(Authenticatable|User|null $user, $categoryId = null, $keyword = null, $region_city = '')
    {
        $now = now();
        $query = JobpositionModel::validPositions();
        if ($categoryId) {
            $query->orderBy(self::getSortKey($categoryId))
                ->whereHas('categories', function ($query) use ($categoryId) {
                    $query->where('category_id', $categoryId);
                });
        } else {
            $query->orderByDesc('id');
        }
        if ($region_city) {
            $query->whereRaw("(region_city=''or region_city='$region_city')");
        } else {
            $query->where('region_city', '');
        }
        if ($keyword) {
            $query->where('position_name', 'like', "%$keyword%");
        }
//        if ($user) {
//            //登录用户做年龄性别限制
//            $age = $user->age();
//            if ($age != -1) {
//                $query->whereRaw("((min_age = 0) or (min_age <= $age))")->whereRaw("((max_age =0) or (max_age >= $age))");
//
//            }
//            //登录用户做性别限制
//            if ($user->gender > 0) {
//                $query->whereRaw("((gender_requirement = 3) or (gender_requirement = $user->gender))");
//            }
//        }
        return $query->paginate();
    }

    /**
     * 根据分类获取排序的key
     * @param int|null $categoryID
     * @return string
     */
    public static function getSortKey(int|null $categoryID): string
    {
        return [
            1 => 'category_sort_1',
            2 => 'category_sort_2',
            3 => 'category_sort_3',
            4 => 'category_sort_4',
            5 => 'category_sort_5',
            6 => 'category_sort_6',
        ][$categoryID] ?? '';
    }

    /**
     * 职位详情
     * @param int $id
     * @param Authenticatable|User|null $user
     * @return array|Builder|Model|object
     * @throws ApiExceptions
     */
    public function detail(int $id, Authenticatable|User|null $user = null)
    {
        DB::enableQueryLog();
        $info = JobpositionModel::query()->validPositions()->find($id);
        if (!$info) {
            throw new ApiExceptions('该职位不存在或已下线');
        }
        return JobpositionModel::query()
            ->where('id', $id)
            ->first();
       
    }

    /**
     * 报名岗位
     * @param int $id
     * @param Authenticatable|User $user
     * @return Builder|Builder[]|Collection|Model|object|null
     * @throws ApiExceptions
     */
    public function signUp(int $id, Authenticatable|User $user)
    {
        if (!$user->name) {
            throw new ApiExceptions('请完善简历信息');
        }
        $cacheKey = "sign-up-jobposition-stacks-{$user->id}";
        $info = JobpositionModel::query()
            ->find($id);
        $info->checkAvailability($user);
        if (!$info) {
            throw new ApiExceptions('该职位不存在或已下线');
        }
        $lock = Cache::lock($cacheKey, 10);
        // if (!$lock->get()) {
        //     throw new ApiExceptions("请求过于频繁请稍后重试");
        // }
//         判断是否报名过
        $doesntExist = SignUpJobpositionModel::query()->where([
            ['user_id', $user->id],
            ['job_position_id', $id],
        ])->doesntExist();
        if ($doesntExist) {
            //减少岗位数量，增加报名人数
            try {
                if ($info->contact_type == JobpositionModel::CONTACT_MOBILE) {
                    $contact = $info->contactPhone()->whereRaw('`number`>`recruit_num`')->first();
                    $info->phone_number = $contact->phone_number ?? '';
                }
                if ($info->contact_type == JobpositionModel::CONTACT_QQ) {
                    $contact = $info->contactQq()->whereRaw('`number`>`recruit_num`')->first();
                    $info->qq_number = $contact->qq_number ?? '';
                    $info->qq_qr_code = $contact->qq_qr_code ?? '';
                }
                if ($info->contact_type == JobpositionModel::CONTACT_WECHAT) {
                    $contact = $info->contactWechat()->whereRaw('`number`>`recruit_num`')->first();
                    $info->wechat_number = $contact->wechat_number ?? '';
                    $info->wechat_qr_code = $contact->wechat_qr_code ?? '';
                }
                if (!$contact) {
                    $info->update([
                        'cur_status' => JobpositionModel::STATUS_OFF_LINE
                    ]);
                    $lock->release();
                    throw new ApiExceptions("报名人数已满");
                }
                $contact->update([
                    'recruit_num' => DB::raw('`recruit_num` + 1'),
                ]);
                $res = JobpositionModel::query()->where([
                    ['id', $id],
                ])->update([
                    'recruit_num' => DB::raw('recruit_num + 1'),
                ]);
            } catch (\Exception $exception) {
                $lock->release();
                throw new ApiExceptions('该职位已报满');
            }
            if (!$res) {
                $lock->release();
                throw new ApiExceptions('该职位已报满');
            }

            //写入报名信息
            $signUpInfo = $info->toArray();
            unset($signUpInfo['id'], $signUpInfo['created_at'], $signUpInfo['updated_at'], $signUpInfo['deleted_at']);
            $signUpInfo['job_position_id'] = $id;
            $signUpInfo['user_id'] = $user->id;
            SignUpJobpositionModel::query()->create($signUpInfo);
        } else {
            $info = SignUpJobpositionModel::query()->where('user_id', $user->id)->where('job_position_id', $id)->first();
            $info->message = MessageModel::query()->where('user_id', $user->id)->where('job_position_id', $id)->get();
        }
        $lock->release();
        //返回岗位信息
        return $info;
    }

    /**
     * 收藏职位
     * @param int $id
     * @param Authenticatable|User $user
     * @return void
     * @throws ApiExceptions
     */
    public function collect(int $id, Authenticatable|User $user): void
    {
        $info = JobpositionModel::query()
            ->find($id);
        if (!$info) {
            throw new ApiExceptions('该职位不存在或已下线');
        }
        $info->checkAvailability($user);
        JobPositionCollectModel::query()->updateOrCreate([
            'job_position_id' => $id,
            'user_id' => $user->id
        ]);
        //职位收藏成功，修改职位收藏数量 
        JobpositionModel::query()->where("id",$id)->increment("collect_num",1);
    }
    
     /**
     * 点赞职位
     * @param int $id
     * @param Authenticatable|User $user
     * @return void
     * @throws ApiExceptions
     */
    public function jobthumbsup(int $id, Authenticatable|User $user): void
    {
        $info = JobpositionModel::query()
            ->find($id);
        if (!$info) {
            throw new ApiExceptions('该职位不存在或已下线');
        }
        $info->checkAvailability($user);
        JobPositionThumbsupModel::query()->updateOrCreate([
            'job_position_id' => $id,
            'user_id' => $user->id
        ]);
        //职位点赞成功，修改职位点赞数量 
        JobpositionModel::query()->where("id",$id)->increment("praise_num",1);
    }

    /**
     * 取消点赞
     * @param int $job_position_id
     * @param Authenticatable|User $user
     * @return void
     * @throws ApiExceptions
     */
    public function jobthumbsupCancel(int $job_position_id, Authenticatable|User $user): void
    {
        $res = JobPositionThumbsupModel::query()->where('job_position_id', $job_position_id)->where('user_id', $user->id)->delete();
        if (!$res) {
            throw new ApiExceptions('取消点赞失败!');
        }
        //取消职位点赞成功，修改职位点赞数量 
        JobpositionModel::query()->where("id",$job_position_id)->decrement("praise_num",1);
    }

    /**
     * 取消收藏 
     * @param int $job_position_id
     * @param Authenticatable|User $user
     * @return void
     * @throws ApiExceptions
     */
    public function collectCancel(int $job_position_id, Authenticatable|User $user): void
    {
        $res = JobPositionCollectModel::query()->where('job_position_id', $job_position_id)->where('user_id', $user->id)->delete();
        if (!$res) {
            throw new ApiExceptions('取消收藏失败!');
        }
        //取消职位收藏成功，修改职位收藏数量 
        JobpositionModel::query()->where("id",$job_position_id)->decrement("collect_num",1);
    }

    /**
     * 收藏列表
     * @param Authenticatable|User $user
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function collectList(Authenticatable|User $user)
    {
        $idArray = JobPositionCollectModel::query()->where('user_id', $user->id)->pluck('job_position_id')->toArray();
        $now = now();


        $query = JobpositionModel::query()
            ->with([
                'categories',
                'company',
            ])
            ->whereIn('id', $idArray)
            ->validPositions();
//        if ($user) {
//            //登录用户做年龄性别限制
//            $age = $user->age();
//            if ($age != -1) {
//                $query->whereRaw("((min_age = 0) or (min_age <= $age))")->whereRaw("((max_age =0) or (max_age >= $age))");
//            }
//            //登录用户做性别限制
//            if ($user->gender > 0) {
//                $query->whereRaw("((gender_requirement = 3) or (gender_requirement = $user->gender))");
//            }
//        }
        return $query->paginate();
    }

    /**
     * 推荐列表
     * @param Authenticatable|User|null $user
     * @return LengthAwarePaginator
     */
    public function recommendList(Authenticatable|User|null $user)
    {
        $idArray = JobPositionRecommendModel::query()->orderBy('sort')->pluck('job_position_id')->toArray();
        $sortString = implode(',', $idArray);
        $query = JobpositionModel::query()
            ->with([
                'categories',
                'company',
            ])
            ->whereIn('id', $idArray)
            ->validPositions()
            ->orderByRaw("field(`id`,$sortString)");

//        if ($user) {
//            //登录用户做年龄性别限制
//            $age = $user->age();
//            if ($age != -1) {
//                $query->whereRaw("((min_age = 0) or (min_age <= $age))")->whereRaw("((max_age =0) or (max_age >= $age))");
//            }
//            //登录用户做性别限制
//            if ($user->gender > 0) {
//                $query->whereRaw("((gender_requirement = 3) or (gender_requirement = $user->gender))");
//            }
//        }
        return $query->paginate();
    }
}
